package com.xianbeiying.app.ckgl.widght;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xianbeiying.app.ckgl.MyApplication;
import com.xianbeiying.app.ckgl.R;
import com.xianbeiying.app.ckgl.activity.LookBigPictureActivity;
import com.xianbeiying.app.ckgl.bean.UrlBean;
import com.xianbeiying.app.ckgl.http.HttpCallBackUtil;
import com.xianbeiying.app.ckgl.model.ImageModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 首页biner图
 */
public class SlideShowView extends FrameLayout implements HttpCallBackUtil{
    // 使用universal-image-loader插件读取网络图片，需要工程导入universal-image-loader-1.8.6-with-sources.jar
    //自动轮播启用开关
    private static boolean isAutoPlay = true;
    //自定义轮播图的资源
    public static List<String> imageUrls=new ArrayList<>();
    public static List<String> tiemUrl=new ArrayList<>();
    public static int selectId;
    //放轮播图片的ImageView 的list
    private List<ImageView> imageViewsList;
    //放圆点的View的list
    private List<View> dotViewsList;

    private ViewPager viewPager;
    //当前轮播页
    private int currentItem = 0;
    //定时任务
    private ScheduledExecutorService scheduledExecutorService;
    private Context context;
    private ImageCycleViewListener mImageCycleViewListener;
    public static ImgViewCallBack imgViewCallBack;
    private ImageModel imageModel;
//    private int [] imgId={R.mipmap.ic_launcher,R.mipmap.ic_launcher};
//    RequestQueue mQueue;
    //Handler
   private TextView time;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            viewPager.setCurrentItem(currentItem);
        }

    };

    public SlideShowView(Context context) {
        this(context, null);

    }

    public SlideShowView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        // TODO Auto-generated constructor stub
    }

    public SlideShowView(final Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
//        mQueue = Volley.newRequestQueue(context);
//        initImageLoader(context);
        imageModel=new ImageModel(context);
        imageModel.addResponseListener(this);
        initData();
        if (isAutoPlay) {
            startPlay();
        }
//        imgViewCallBack = new ImgViewCallBack() {
//            @Override
//            public void imgview(String[] img) {
//                imageUrls = img;
//                initUI(context);
//            }
//        };
    }


//    public static void ShowImage(String[] image){
//         imageUrls=image;
//    }


    /**
     * 开始轮播图切换
     */
    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
    }

    /**
     * 停止轮播图切换
     */
    public void stopPlay() {
        scheduledExecutorService.shutdown();
    }

    /**
     * 初始化相关Data
     */
    private void initData() {
        imageViewsList = new ArrayList<ImageView>();
        dotViewsList = new ArrayList<View>();
        imageUrls.clear();
        imageModel.ImageHistoLogins(com.xianbeiying.app.ckgl.util.DataUtil.getLoactionTime(), MyApplication.devicesBean.getGREENHOUSE().get(0).getGreenhouseId(),true);
        // 一步任务获取图片
//        getSlide();
//        new GetListTask().execute("");
    }
    /**
     * 初始化Views等UI
     */
    private void initUI(final Context context){
//        LogUtils.i("数组长度："+imageUrls.length);

        if (imageUrls == null || imageUrls.size() == 0)
            return;
//        if(imgId==null||imgId.length==0)
//            return;
        LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this, true);
        LinearLayout dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
        time=(TextView) findViewById(R.id.time);
        dotLayout.removeAllViews();

//        // 热点个数与图片特殊相等
//        for (int i = 0; i < imgId.length; i++) {
//            ImageView view = new ImageView(context);
//            view.setTag(i);
////            if(i==0)//给一个默认图  建议做一个灰色的不含有具体内容的默认加载图片
////                view.setBackgroundResource(R.drawable.appmain_subject_1);
//
//            view.setScaleType(ImageView.ScaleType.FIT_XY);
//            imageViewsList.add(view);
//
//            ImageView dotView = new ImageView(context);
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//            params.leftMargin = 4;
//            params.rightMargin = 4;
//            dotLayout.addView(dotView, params);
//            dotViewsList.add(dotView);
//
//            final int finalI = i;
//            view.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Log.e("---", "aa" + finalI);
//                }
//            });
//
//        }
//        Log.e("---", imageUrls.size() + "");
        for (int i = 0; i < imageUrls.size(); i++) {
            ImageView view = new ImageView(context);
            view.setTag("http://"+ MyApplication.IP+ UrlBean.IMAGES+imageUrls.get(i));

//            if(i==0)//给一个默认图  建议做一个灰色的不含有具体内容的默认加载图片
//                view.setBackgroundResource(R.drawable.appmain_subject_1);

            view.setScaleType(ImageView.ScaleType.FIT_XY);
            imageViewsList.add(view);

            ImageView dotView = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.leftMargin = 4;
            params.rightMargin = 4;
            dotLayout.addView(dotView, params);
            dotViewsList.add(dotView);
            final int finalI = i;
            selectId=i;
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Log.e("---", "aa" + finalI);
                    context.startActivity(new Intent().setClass(context,LookBigPictureActivity.class).putExtra("imgUrl",imageUrls.get(finalI)));
                }
            });

        }
        time.setText(tiemUrl.get(0));
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPager.setFocusable(true);

        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPageChangeListener());
    }

    @Override
    public void onCallBackData(String url, Object content) {
        JSONArray jsonArray= JSON.parseArray(content+"");
        if(jsonArray!=null&&jsonArray.size()!=0){
            int size=jsonArray.size();
            for(int i=0;i<size;i++){
                imageUrls.add(jsonArray.getString(i));
                String [] dateStr=jsonArray.getString(i).split("\\/");
                String [] date=dateStr[dateStr.length-1].split("\\.");
                tiemUrl.add(date[0]);
            }
            initUI(context);

        }
    }


    /**
     * 填充ViewPager的页面适配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public void destroyItem(View container, int position, Object object) {
            // TODO Auto-generated method stub
            //((ViewPag.er)container).removeView((View)object);
            ((ViewPager) container).removeView(imageViewsList.get(position));
        }

        @Override
        public Object instantiateItem(View container, int position) {
            ImageView imageView = imageViewsList.get(position);
              //设置图片
            ImageLoader.getInstance().displayImage(imageView.getTag() + "", imageView);
//            imageView.setImageResource(imgId[position]);
            ((ViewPager) container).addView(imageViewsList.get(position));
            return imageViewsList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return imageViewsList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public Parcelable saveState() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void finishUpdate(View arg0) {
            // TODO Auto-generated method stub
        }
    }

    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     */
    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
        boolean isAutoPlay = false;
        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        viewPager.setCurrentItem(0);
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1);
                    }
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageSelected(int pos) {
            // TODO Auto-generated method stub
            currentItem = pos;
            time.setText(tiemUrl.get(pos));
            for (int i = 0; i < dotViewsList.size(); i++) {
                if (i == pos){
                    ((View) dotViewsList.get(pos)).setBackgroundResource(R.mipmap.dot_focus);
                } else {
                    ((View) dotViewsList.get(i)).setBackgroundResource(R.mipmap.dot_blur);
                }
            }
        }


    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            synchronized (viewPager) {
                currentItem = (currentItem + 1) % imageViewsList.size();
                handler.obtainMessage().sendToTarget();
            }
        }
    }

    /**
     * 销毁ImageView资源，回收内存
     */
    private void destoryBitmaps() {
//
//        for (int i = 0; i < imgId.length; i++) {
//            ImageView imageView = imageViewsList.get(i);
//            Drawable drawable = imageView.getDrawable();
//            if (drawable != null) {
//                //解除drawable对view的引用
//                drawable.setCallback(null);
//            }
//        }

        for (int i = 0; i < imageUrls.size(); i++) {
            ImageView imageView = imageViewsList.get(i);
            Drawable drawable = imageView.getDrawable();
            if (drawable != null) {
                //解除drawable对view的引用
                drawable.setCallback(null);
            }
        }
    }
    /**
     * 轮播控件的监听事件
     *
     * @author minking
     */
        public static interface ImageCycleViewListener {
        /**
         * 单击图片事件
         *
         * @param
         */
        public void onImageClick(OnClickListener listener);
    }
    //可设置参数,对不同的轮播界面进行图片展示
}